﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace PortDetection.Class
{
    class ProcessCalss
    {

        /// <summary>
        /// 获取外部程序ID
        /// </summary>
        /// <param name="processName">外部程序名称</param>
        /// <returns></returns>
        public static int GetPidByProcessName(string processName)
        {
            try
            {
                Process[] arrayProcess = Process.GetProcessesByName(processName);

                foreach (Process p in arrayProcess)
                {
                    return p.Id;
                }
                return 0;
            }
            catch (Exception)
            {

                throw;
            }
            
        }

        /// <summary>
        /// 运行外部程序
        /// </summary>
        /// <param name="FileName"></param>
        public static void OpenProcedure(string FileName)
        {
            try
            {
                Console.WriteLine("指定程序未运行");
                Process p = new Process();
                p.StartInfo.FileName = FileName;
                p.StartInfo.WorkingDirectory = Path.GetDirectoryName(FileName);
                //p.StartInfo.UseShellExecute = false;
                //p.StartInfo.CreateNoWindow = true;
                p.Start();
            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);
            }

            
        }

        /// <summary>
        /// 关闭进程
        /// </summary>
        /// <param name="id">进程ID</param>
        public static void CloseProcedure(int id)
        {
            try
            {
                Process proApp = Process.GetProcessById(id);
                Console.WriteLine(proApp.ProcessName);
                // 处理该进程  
                proApp.Kill();
                proApp.Close();
            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);
                
            }
           
        }

        /// <summary>
        /// 关闭占用端口的进程（UDP端口）
        /// </summary>
        /// <param name="Port"></param>
        public static void CloseOccupancyProcedure(string Port)
        {
            try
            {
                Process pro = new Process();
                // 设置命令行、参数  
                pro.StartInfo.FileName = "cmd.exe";
                pro.StartInfo.UseShellExecute = false;
                pro.StartInfo.RedirectStandardInput = true;
                pro.StartInfo.RedirectStandardOutput = true;
                pro.StartInfo.RedirectStandardError = true;
                pro.StartInfo.CreateNoWindow = true;
                // 启动CMD  
                pro.Start();
                // 运行端口检查命令  
                pro.StandardInput.WriteLine("netstat -ano");
                pro.StandardInput.WriteLine("exit");
                // 获取结果  
                Regex reg = new Regex("//s+", RegexOptions.Compiled);
                string line = null;
                while ((line = pro.StandardOutput.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (line.StartsWith("UDP", StringComparison.OrdinalIgnoreCase))
                    {
                        line = reg.Replace(line, ",");
                        line = line.Replace(" ", ",");
                        string[] arr = line.Split(',');
                        if (arr[4].EndsWith(string.Format(":{0}", Port)))
                        {
                            Console.WriteLine("{0}端口的进程ID：{1}", Port, arr[arr.Length - 1]);
                            int pid = Int32.Parse(arr[arr.Length - 1]);
                            Process proApp = Process.GetProcessById(pid);
                            // 处理该进程  
                            proApp.Kill();
                            proApp.Close();
                            break;
                        }
                    }
                }
                pro.Close();
            }
            catch (Exception ex)
            {
                WriteLog.DataLog(ex);
            }

        }


    }
}
